package com.qq.spirit;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Properties;
import java.util.concurrent.ConcurrentHashMap;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.log4j.Appender;
import org.apache.log4j.Layout;
import org.apache.log4j.Logger;
import org.apache.log4j.PatternLayout;
import org.apache.log4j.PropertyConfigurator;
import org.apache.log4j.RollingFileAppender;

public class LoggerUtil
{
	private static ConcurrentHashMap<Integer, Logger> logMap = new ConcurrentHashMap<Integer, Logger>();

	private static Logger getLogger(int gid)
	{
		if (!logMap.containsKey(gid))
		{
			synchronized (logMap)
			{
				if (!logMap.containsKey(gid))
				{
					try
					{
						Calendar cl = Calendar.getInstance();
						String filename = gid + "$" + cl.get(Calendar.YEAR) + "_" + cl.get(Calendar.MONTH) + "_" + cl.get(Calendar.DAY_OF_MONTH) + ".txt";
						File f = new File(filename);
						if (!f.exists())
						{
							f.createNewFile();
						}
						Logger myTest = Logger.getLogger("" + gid);
						Layout layout = new PatternLayout("%d{yyy-MM-dd HH:mm:ss } - %m%n");
						Appender appender = new RollingFileAppender(layout, f.getAbsolutePath(), true);
						Appender appender2 = new org.apache.log4j.ConsoleAppender(layout);
						myTest.addAppender(appender);
						myTest.addAppender(appender2);
						logMap.put(gid, myTest);
					} catch (IOException e)
					{
						e.printStackTrace();
					}
				}
			}
		}
		return logMap.get(gid);
	}

	public static void error(int gid, Exception ex)
	{
		getLogger(gid).error(ex.getMessage(), ex);
	}

	public static void logger(int gid, String s)
	{
		getLogger(gid).debug(String.format("%s|%s", GameUserInfoUtil.getGameName(gid), s));
	}

	public static void sys(String s)
	{
		getLogger(0).info(s);
	}

	public static void info(int gid, String s)
	{
		getLogger(gid).info(String.format("%s|%s", GameUserInfoUtil.getGameName(gid), s));
	}

	public static void debug(int gid, String s)
	{
		getLogger(gid).debug(String.format("%s|%s", GameUserInfoUtil.getGameName(gid), s));
	}
}
